package com.zdya.combatdocuments.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;

import java.security.KeyPair;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:HYZ
 * @Date:2023-6-12
 */
public class SmUtils {


//    String text = "我是一段测试aaaa";
//
//    KeyPair pair = SecureUtil.generateKeyPair("SM2");
//    byte[] privateKey = pair.getPrivate().getEncoded();
//    byte[] publicKey = pair.getPublic().getEncoded();
//
//    SM2 sm2 = SmUtil.sm2(privateKey, publicKey);
//    // 公钥加密，私钥解密
//    String encryptStr = sm2.encryptBcd(text, KeyType.PublicKey);
//    String decryptStr = StrUtil.utf8Str(sm2.decryptFromBcd(encryptStr, KeyType.PrivateKey));


    public static void main(String[] args) {
        Map<String, String> map = creatKeyPair();
        String publicKey = map.get("publicKey");
        String privateKey = map.get("privateKey");

        String encrypt = encrypt(publicKey, "123");
        System.out.println(encrypt);

        String decrypt = decrypt(privateKey, encrypt);
        System.out.println(decrypt);


    }






    /**
     * 生成密钥对
     * @return
     */
    public static Map<String, String> creatKeyPair() {
        Map<String, String> map = new HashMap<>();
        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        byte[] privateKey = pair.getPrivate().getEncoded();
        byte[] publicKey = pair.getPublic().getEncoded();
        map.put("publicKey", Base64.getEncoder().encodeToString(publicKey));
        map.put("privateKey", Base64.getEncoder().encodeToString(privateKey));
        return map;
    }

    /**
     * 加密
     * @param publicKey  公钥
     * @param data       数据原文
     * @return  密文
     */
    public static String encrypt(String publicKey,String data){
        SM2 sm2 = SmUtil.sm2(null, Base64.getDecoder().decode(publicKey));
        return sm2.encryptBcd(data, KeyType.PublicKey);
    }

    /**
     * 解密
     * @param privateKey 私钥
     * @param data       密文
     * @return  数据原文
     */
    public static String decrypt(String privateKey,String data){
        SM2 sm2 = SmUtil.sm2(Base64.getDecoder().decode(privateKey), null);
        return StrUtil.utf8Str(sm2.decryptFromBcd(data, KeyType.PrivateKey));
    }

}
